<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import io, { Socket } from "socket.io-client";
import { baseURL } from "@/utils/request";
import { useUserStore } from '@/stores';
import { useRoute } from 'vue-router';
import { nextTick, onMounted, onUnmounted, ref } from 'vue';
import { Message, TimeMessages } from '@/types/room';
import { MsgType } from '@/enum';
import { ConsultOrderItem, Image } from '@/types/consult';
import { getConsultOrderDetail } from '@/services/consult';
import dayjs from 'dayjs';
import { showToast } from 'vant';
// import { log } from 'console';
const store=useUserStore()
const route=useRoute()
let socket:Socket
const list=ref<Message[]>([])
const initialMsg=ref(true)
//获取订单信息
const consult=ref<ConsultOrderItem>()
const loadConsult=async()=>{
 const res= await getConsultOrderDetail(route.query.orderId as string)
 consult.value=res.data
//  console.log(consult.value);

}
onMounted(()=>{
  loadConsult()
  socket=io(baseURL,{
    auth:{
      token:`Bearer ${store.user?.token}`
    },
    query:{
      orderId:route.query.orderId
    }
  })
  socket.on('connect',()=>{
    console.log('连接成功');

  })
  socket.on('disconnect',()=>{
    console.log('断开连接');

  })
  socket.on('error',(err)=>{
    console.log('发生错误',err);
  })
  //接受默认消息
  socket.on('chatMsgList',({data}:{data:TimeMessages[]})=>{
   const arr:Message[]=[]

    data.forEach((item,i) => {
      //记录每一段消息中的最早的时间
       if(i===0) time.value=item.createTime
      arr.push({
        createTime:item.createTime,
        id:item.createTime,
        msg:{content: item.createTime},
        msgType: MsgType.Notify
      })
      arr.push(...item.items)
    });
    list.value.unshift(...arr)
    loading.value=false
    if(!arr.length) return showToast('没有更多聊天记录了')
    if(initialMsg.value){
      nextTick(()=>{
        window.scrollTo(0,document.body.scrollHeight)
        initialMsg.value=false
      })
    }
  })
  //监听订单状态变化
  socket.on('statusChange',()=>loadConsult())
  //接收消息
  socket.on('receiveChatMsg',async(event)=>{
    console.log(event);
    list.value.push(event)
    await nextTick()
    window.scroll(0,document.body.scrollHeight)
  })
})

onUnmounted(()=>{
  socket.close()
})
//发送消息
const onSendText=(text:string)=>{
  socket.emit('sendChatMsg',{
    from:store.user?.id,
    to:consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg:{
      content:text
    }
  })

}
//发送图片
const onSendImage=(image:Image)=>{
  socket.emit('sendChatMsg',{
    from:store.user?.id,
    to:consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg:{
      picture:image
    }
  })
}
const loading=ref(true)
const time=ref( dayjs().format('YYYY-MM--DD HH:mm:ss'))
const onRefresh=()=>{
  socket.emit('getChatMsgList',20,time.value,consult.value?.id)
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown"></room-status>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">

      <RoomMessage v-for="item in list" :key="item.id" :item="item" ></RoomMessage>
    </van-pull-refresh>
    <room-action
    @send-text="onSendText"
    @send-image="onSendImage"
     :disabled="consult?.status !==3?true:false"
     ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
